package com.itheima.mp.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import com.itheima.mp.utils.PageDtoConvertUtil;
import com.itheima.mp.utils.PageQueryConvertUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deductionBalanceById(Long id, Integer money) {
        // 1.查询用户
        User user = this.getById(id);
        // 2.校验用户状态
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户已冻结，无法操作");
        }
        // 3.校验余额是否充足
        if (user.getBalance() < money) {
            throw new RuntimeException("余额不足，无法操作");
        }
        // 4.扣减余额
        // baseMapper.deductBalanceById(id, money);
        int remainBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, remainBalance)
                .set(remainBalance == 0, User::getStatus, UserStatus.FROZEN)
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance())
                .update();
    }

    @Override
    public List<User> queryUsers(UserQuery query) {
        /**
         * name：用户名关键字，可以为空
         * status：用户状态，可以为空
         * minBalance：最小余额，可以为空
         * maxBalance：最大余额，可以为空
         */

        return lambdaQuery()
                .like(query.getName() != null, User::getUsername, query.getName())
                .eq(query.getStatus() != null, User::getStatus, query.getStatus())
                .ge(query.getMinBalance() != null, User::getBalance, query.getMinBalance())
                .le(query.getMaxBalance() != null, User::getBalance, query.getMaxBalance())
                .list();
    }

    @Override
    public UserVO queryUserAndAddressById(Long id) {
        User user = getById(id);
        if (user == null) {
            return null;
        }
        List<Address> list = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, id)
                .list();
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        userVO.setAddress(BeanUtil.copyToList(list, AddressVO.class));
        return userVO;
    }

    @Override
    public List<UserVO> queryUsersWithAddress(List<Long> ids) {
        List<User> users = listByIds(ids);
        if (CollUtil.isEmpty(users)) {
            return Collections.emptyList();
        }
        List<UserVO> userVOS = BeanUtil.copyToList(users, UserVO.class);

        List<Address> addresses = Db.lambdaQuery(Address.class)
                .in(Address::getUserId, ids)
                .list();
        if (CollUtil.isNotEmpty(addresses)) {
            addresses.stream()
                    .collect(Collectors.groupingBy(Address::getUserId))
                    .forEach((userId, addressList) -> {
                        userVOS.stream()
                                .filter(userVO -> userVO.getId().equals(userId))
                                .findFirst()
                                .ifPresent(userVO -> userVO.setAddress(BeanUtil.copyToList(addressList, AddressVO.class)));
                    });
        }

        return userVOS;
    }

    @Override
    public PageDTO<UserVO> queryUsersPage(UserQuery query) {
        // 1.构建分页条件
        Page<User> page;
        if (StrUtil.isNotBlank(query.getSortBy())) {
            // page = query.toMpPage(query.getSortBy(), query.getIsAsc());
            page = PageQueryConvertUtil.MyBatisPlus.toMpPage(query, query.getSortBy(), query.getIsAsc());
        } else {
            // page = query.toMpPageDefaultSortByUpdateTimeDesc();
            page = PageQueryConvertUtil.MyBatisPlus.toMpPageDefaultSortByUpdateTimeDesc(query);
        }

        // 2.分页查询
        lambdaQuery()
                .like(query.getName() != null, User::getUsername, query.getName())
                .eq(query.getStatus() != null, User::getStatus, query.getStatus())
                .ge(query.getMinBalance() != null, User::getBalance, query.getMinBalance())
                .le(query.getMaxBalance() != null, User::getBalance, query.getMaxBalance())
                .page(page);

        // 3.封装返回
        // return PageDTO.of(page, UserVO.class);
        return PageDtoConvertUtil.MyBatisPlus.convertToVOPage(page, user -> {
            UserVO vo = BeanUtil.copyProperties(user, UserVO.class);
            vo.setUsername(user.getUsername().substring(0, user.getUsername().length() - 2) + "**");
            return vo;
        });
    }
}
